package com.notary.tx_live_plugin.util;

import android.Manifest;
import android.app.Activity;
import android.content.Context;

import androidx.fragment.app.FragmentActivity;

import com.notary.tx_live_plugin.widget.TxLiveChatMeetView;

import java.lang.ref.WeakReference;
import java.util.Map;

import io.flutter.plugin.common.PluginRegistry;

/**
 * 推流管理，摄像机权限处理
 */
public class ChatManager implements PluginRegistry.RequestPermissionsResultListener {

    private TxLiveChatMeetView mTxLiveChatView;
    private OnChatCallback mOnChatCallback;
    private WeakReference<Context> mContextWeak;

    public static ChatManager getInstance() {
        return ChatManagerHolder.instance;
    }

    private ChatManager() {
    }

    private static final class ChatManagerHolder{
        private static final ChatManager instance = new ChatManager();
    }

    /**
     * 设置推流view
     */
    public void setChatView(TxLiveChatMeetView chatMeetView) {
        this.mTxLiveChatView = chatMeetView;
        if (chatMeetView != null) {
            chatMeetView.setOnChatCallback(ChatManager.this::callback);
        }
    }

    public void setContext(Context context) {
        if (mContextWeak != null) mContextWeak.clear();
        if (context != null) this.mContextWeak = new WeakReference<>(context);
    }

    public void setOnChatCallback(OnChatCallback onPushCallback) {
        this.mOnChatCallback = onPushCallback;
    }

    public void clear(){
        setChatView(null);
        setContext(null);
        setContext(null);
    }

    @Override
    public boolean onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == TxLivePluginConstant.REQUEST_TAKE_PUSH) {
            if (TxLiveUtils.isPermissionOK(permissions, grantResults)) {
                if (mTxLiveChatView != null) mTxLiveChatView.initChatView();
            }
            return true;
        }
        return false;
    }

    /**
     * 添加推流控件前，请求权限
     */
    public void requestPermissionForPush() {
        if (mContextWeak == null || mContextWeak.get() == null) {
            if (mTxLiveChatView != null) mTxLiveChatView.initChatView();
            return;
        }
        Context activity = mContextWeak.get();
        if(activity instanceof Activity) {
            //直播录像
            TxLiveUtils.requestPermission(activity instanceof FragmentActivity
                            ? (FragmentActivity)activity : (Activity)activity,
                    TxLivePluginConstant.REQUEST_TAKE_PUSH,
                    Manifest.permission.CAMERA,
                    Manifest.permission.RECORD_AUDIO);
        }else{
            if (mTxLiveChatView != null) mTxLiveChatView.initChatView();
        }
    }

    public void onResume() {
//        if (checkChatView(TxConstant.ChatMethod.onResume)) {
//            return;
//        }
//        mTxLiveChatView.onResume();
    }

    public void onPause() {
//        if (checkChatView(TxConstant.ChatMethod.onPause)) {
//            return;
//        }
//        mTxLiveChatView.onPause();
    }

    public void onDestroy() {
        if (checkChatView(TxConstant.ChatMethod.onDestroy)) {
            return;
        }
        mTxLiveChatView.onDestroy();
    }

    public boolean isCreating() {
        if (checkChatView(TxConstant.ChatMethod.isCreating)) {
            return false;
        }
        return mTxLiveChatView.isCreating();
    }

    public boolean isOpenAudio() {
        if (checkChatView(TxConstant.ChatMethod.isOpenAudio)) {
            return false;
        }
        return mTxLiveChatView.isOpenAudio();
    }

    public Boolean switchAudio() {
        if (checkChatView(TxConstant.ChatMethod.switchAudio)) {
            return false;
        }
        return mTxLiveChatView.switchAudio();
    }


    public void stopChat() {
        if (checkChatView(TxConstant.ChatMethod.stopChat)) {
            return;
        }
        mTxLiveChatView.stopChat();
    }

    /**
     * 开始推流
     *
     * @param data map参数，key包含 url、serverTime
     */
    public boolean startChat(Object data) {
        if (checkChatView(TxConstant.ChatMethod.startChat)) {
            return false;
        }
        Integer sdkAppId = null, roomId = null;
        String userId = null, userSign = null;
        if (data instanceof Map) {
            Map<String, Object> d = (Map<String, Object>) data;
            sdkAppId = (Integer) d.get(TxConstant.ChatMethod.Key.sdkAppId);
            roomId = (Integer) d.get(TxConstant.ChatMethod.Key.roomId);
            userId = (String) d.get(TxConstant.ChatMethod.Key.userId);
            userSign = (String) d.get(TxConstant.ChatMethod.Key.userSign);
        }
        if (sdkAppId == null || roomId == null || userId == null || userSign == null) {
            callback("error", "method startChat need param,sdkAppId " + sdkAppId
                    + " roomId " + roomId + " userId " + userId + " userSign " + userSign);
            return false;
        }
        mTxLiveChatView.startCharMeet(sdkAppId,userId,userSign,roomId);
        return true;
    }

    private void callback(String method, Object data) {
        if (mOnChatCallback != null) {
            mOnChatCallback.callback(method, data);
        }
    }

    /**
     * 确认控件是否为空
     */
    private boolean checkChatView(String methodName) {
        if (mTxLiveChatView == null) {
            callback("error", "chat view is empty for method " + methodName);
            return true;
        }
        return false;
    }

    /**
     * 视频会议功能，对flutter的回调
     */
    public interface OnChatCallback {
        void callback(String methodName, Object data);
    }
}
